package emd24.telstudyresources;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

/**
 * SCRAPPED CLASS!!!!!!!!!!!
 * This class was used to load the quiz.
 * 
 * @author Owner
 *
 */
public class QuizLoader extends AsyncTask<String, Void, Quiz>{

	ProgressDialog d;

	protected void onPreExecute() {
		super.onPreExecute();
		d = new ProgressDialog(null);
		d.setMessage("Loading Quiz");
		d.setIndeterminate(false);
		d.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		d.setCancelable(true);
		d.show();
	}
	protected Quiz doInBackground(String... params) {
		String parsedResult = null;
		try {
			// Get the JSON from online
			Log.e("QuizLoader"," QuizLoader: Starting Parse");
			URL url = new URL(params[0]);
			Log.e("QuizLoader"," QuizLoader: Starting Connection");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			Log.e("QuizLoader"," QuizLoader:  Opening Connection");
			conn.connect(); //Open connection, code will fail here if there is no network connection
			InputStream is = conn.getInputStream();
			Log.e("QuizLoader"," QuizLoader:  Closing Connection");
			parsedResult = getStringFromInputStream(is);	
			Log.e("QuizLoader: Parsed", "QuizLoader " + parsedResult);
			Log.e("QuizLoader: Parsed", "QuizLoader " + parsedResult);
			is.close();

			// Create the quiz
			return new Quiz(new JSONObject(parsedResult), 5, true);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}
	protected void onPostExecute(Quiz q){
		d.dismiss();
	}
	private static String getStringFromInputStream(InputStream is) {

		BufferedReader br = null;
		StringBuilder sb = new StringBuilder();

		String line;
		try {
			br = new BufferedReader(new InputStreamReader(is));
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb.toString();
	}
}



